package com.by_man.repository;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * 开启一个后台服务处理所有的网络请求，数据更新
 * Created by man on 2017-03-03.
 */
public class BackgroundService extends Service {
    // 网络请求队列
    private RequestQueue rQueue;
    private NetworkDataManager manager;

    @Override
    public void onCreate() {
        // 初始化队列
        rQueue = Volley.newRequestQueue(this);
        rQueue.start();
        // 创建网络任务管理，开启管理
        manager = new NetworkDataManager(rQueue);
        LocalDataManager.manager = manager;
        LocalDataManager.service = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int starId) {
        // 希望服务持续运行所有返回START_STICKY
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d("BackgroundService", "服务停止！");
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        BackgroundService getService() {
            return BackgroundService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public RequestQueue getQueue() {
        if (null == rQueue) {
            rQueue = Volley.newRequestQueue(this);
        }

        return rQueue;
    }

    public NetworkDataManager getManager() {
        if (null == manager) {
            manager = new NetworkDataManager(getQueue());
        }

        return manager;
    }

}
